package downloadUtils

import (
	logger "downloadDanceVideo/logutils"
	"io"
	"net/http"
	"os"
	"strings"
)

func DownloadFromUrl(url, newName string) {

	tokens := strings.Split(url, "/")
	fileName := tokens[len(tokens)-1] //xxxxxx.mp4

	nameAndSurfix := strings.Split(fileName, ".")

	_surfix := ""
	if len(nameAndSurfix) == 2 {
		_surfix = nameAndSurfix[1]
	} else {
		panic("cannot find a surfix to append")
	}

	if newName != "" {
		fileName = newName + "." + _surfix
	}

	logger.MULTITRACE.Println("Downloading", url, "with name :", fileName)

	// TODO: check file existence first with io.IsExist
	output, err := os.Create(fileName)
	if err != nil {
		logger.MULTITRACE.Println("Error while creating", fileName, "-", err)
		return
	}
	defer output.Close()

	response, err := http.Get(url)
	if err != nil {
		logger.MULTITRACE.Println("Error while downloading", url, "-", err)
		return
	}
	defer response.Body.Close()

	n, err := io.Copy(output, response.Body)
	if err != nil {
		logger.MULTITRACE.Println("Error while downloading", url, "-", err)
		return
	}

	logger.MULTITRACE.Println(n, "bytes downloaded.")
}
